package com.pingan.haofang.searchcloud.common.configuration;

import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

@Configuration
public class ScheduleConfiguration {

    @Autowired
    private JobFactory jobFactory;

    @Autowired
    DataSource dataSource;

    @Value("${quartz.scheduler.instanceName:scheduler}")
    String instanceName;

    @Value("${quartz.scheduler.isWorker:true}")
    boolean isWorker;

    private Properties managerProperties() throws IOException {
        Properties prop = new Properties();
        prop.load(new ClassPathResource("/quartz-manager.properties").getInputStream());
        return prop;
    }

    private Properties workerProperties() throws IOException {
        Properties prop = new Properties();
        prop.load(new ClassPathResource("/quartz-worker.properties").getInputStream());
        return prop;
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setQuartzProperties(isWorker ? workerProperties() : managerProperties());
        factory.setSchedulerName(instanceName);
        factory.setDataSource(dataSource);
        factory.setJobFactory(jobFactory);
        factory.setOverwriteExistingJobs(true);
        return factory;
    }


}
